# 发送验证码脚本
from django.core.mail import send_mail, EmailMessage
from django.conf import settings

from typing import List

import json

# 阿里云短信sdk
from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient


# 发送邮件
def send_code_email(email, code):
    body_str = "您正在注册 Tedu-AI 助手账户，注册验证码为 {}，请不要告诉他人。如非本人操作，请忽略此邮件。".format(code)
    to_list = [email]

    email = EmailMessage(
        subject = 'Tedu-AI 注册验证码',
        body = body_str,
        from_email = '18201419965@163.com',
        to = to_list,
    )

    # 发送邮件
    try:
        email.send(fail_silently=False)
        return 1
    except:
        return 0


class SendCodePhone:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Dysmsapi20170525Client:
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        """
        # 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        # 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378659.html。
        config = open_api_models.Config(
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
            access_key_id=settings.ALI_SMS_CONF['AccessKey'],
            # 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
            access_key_secret=settings.ALI_SMS_CONF['AccessSecret']
        )
        # Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = f'dysmsapi.aliyuncs.com'
        return Dysmsapi20170525Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = SendCodePhone.create_client()
        code_mes_dict = {
            "code": args[1]
            }
        code_mes_str = json.dumps(code_mes_dict)
        send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
            sign_name=settings.ALI_SMS_CONF['SignName'],
            phone_numbers=args[0],
            template_code=settings.ALI_SMS_CONF['TemplateCode'],
            template_param=code_mes_str
        )
        try:
            # 复制代码运行请自行打印 API 的返回值
            send_resp = client.send_sms_with_options(send_sms_request, util_models.RuntimeOptions())
            code = send_resp.body.code
            if UtilClient.equal_string(code, 'OK'):
                return 1
            else:
                return 0
        except Exception as error:
            # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            # 错误 message
            print(error.message)
            # 诊断地址
            print(error.data.get("Recommend"))
            UtilClient.assert_as_string(error.message)
            return 0

    # @staticmethod
    # async def main_async(
    #     args: List[str],
    # ) -> None:
    #     client = SendCodePhone.create_client()
    #     code_mes_dict = {
    #         "code": args[1]
    #         }
    #     code_mes_str = json.dumps(code_mes_dict)
    #     send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
    #         sign_name='范琪',
    #         phone_numbers=args[0],
    #         template_code='SMS_471365282',
    #         template_param=code_mes_str
    #     )
    #     try:
    #         # 复制代码运行请自行打印 API 的返回值
    #         await client.send_sms_with_options_async(send_sms_request, util_models.RuntimeOptions())
    #     except Exception as error:
    #         # 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
    #         # 错误 message
    #         print(error.message)
    #         # 诊断地址
    #         print(error.data.get("Recommend"))
    #         UtilClient.assert_as_string(error.message)

